<?php
// +----------------------------------------------------------------------
// | Desc: [ Better-钱包记录 ]
// +----------------------------------------------------------------------
// | Author: huangzhen_20210406
// +----------------------------------------------------------------------

namespace app\common\model;
use think\facade\Db;

class UserCashLog extends Common
{
    //---------------------------------------------后端---------------------------------------------------------------
    /**
     * 返回layui的table所需要的格式
     * @param $post
     * @param $user_id
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function tableDataAdmin($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];
        if(isset($post['user_name']) && !empty($post['user_name'])){
            $where[] = ['username', 'like', '%'.$post['user_name'].'%'];
        }
        if(isset($post['desc']) && !empty($post['desc'])){
            $where[] = ['ucl.desc', 'like', '%'.$post['desc'].'%'];
        }
        if(isset($post['datetime']) && !empty($post['datetime'])){
            $time_list = explode('_' , $post['datetime']);
            $start_time = strtotime($time_list[0] . " 00:00:00");
            $end_time   = strtotime($time_list[1] . " 23:59:59");
            $where[] = ['ucl.ctime', 'between', "{$start_time},{$end_time}"];
        }
        if(isset($post['bank']) && strlen($post['bank'])>0){
            $where[] = ['bank', '=', $post['bank']];
        }
        $list = Db::name('user_cash_log')->alias('ucl')
            ->leftJoin('user u','u.id=ucl.user_id')
            ->field('ucl.id,username,ucl.ctime,ucl.desc,ucl.amount,ucl.balance,ucl.type,ucl.card_type')
            ->order('ucl.id desc,ucl.ctime desc')
            ->where($where)
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();
        $data = $list['data'];
        foreach ($data as &$v){
            $type = $v['type'];
            if($type == 1){
                $v['amount'] = -getSprintf($v['amount']);
            }
        }
        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $data,
            'count' => $list['total'],
        ];
    }

    //---------------------------------------------前端---------------------------------------------------------------
    /**
     * 返回layui的table所需要的格式
     * @param $post
     * @param $user_id
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function tableDataIndex($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];
        $where[] = ['u.id', '=', $post['user_id']];
        if(isset($post['desc']) && !empty($post['desc'])){
            $where[] = ['ucl.desc', 'like', '%'.$post['desc'].'%'];
        }
        if(isset($post['datetime']) && !empty($post['datetime'])){
            $time_list = explode('_' , $post['datetime']);
            $start_time = strtotime($time_list[0] . " 00:00:00") - 8*60*60;
            $end_time   = strtotime($time_list[1] . " 23:59:59") - 8*60*60;
            $where[] = ['ucl.ctime', 'between', "{$start_time},{$end_time}"];
        }

        $list = Db::name('user_cash_log')->alias('ucl')
            ->leftJoin('user u','u.id=ucl.user_id')
            ->field('ucl.id,username,ucl.ctime,ucl.desc,ucl.amount,ucl.balance,ucl.type')
            ->order('ucl.ctime desc')
            ->where($where)
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();

        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

    /**
     * 返回layui的table所需要的格式
     * @param $post
     * @param $user_id
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function tableData($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];
        if(isset($post['desc']) && !empty($post['desc'])){
            $where[] = ['ucl.desc', 'like', '%'.$post['desc'].'%'];
        }
        if(isset($post['datetime']) && !empty($post['datetime'])){
            $time_list = explode('_' , $post['datetime']);
            $start_time = strtotime($time_list[0] . " 00:00:00") - 8*60*60;
            $end_time   = strtotime($time_list[1] . " 23:59:59") - 8*60*60;
            $where[] = ['ucl.ctime', 'between', "{$start_time},{$end_time}"];
        }

        $list = Db::name('user_cash_log')->alias('ucl')
            ->field('ucl.ctime,ucl.desc,ucl.amount,ucl.balance,ucl.type')
            ->order('ucl.ctime desc')
            ->where($where)
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();

        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

    /**
     * 会员到首页显示充值列表(只显示成功的)
     * @param $post
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function indexHomeTable($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];
        $where[] = ['user_id', '=', $post['user_id']];
        $list = Db::name('user_cash_log')
            ->where($where)
            ->order('ctime desc')
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();
        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

    public static function getHomeDataOne($param = NULL)
    {
        $insert_data = [
            "data" => "updateAll",
            "ctime"=> getUtcTime()
        ];
        //拒付+0验证
        $profit_cd = Db::name('server_cd')->where(['is_action'=>1])->sum('server_amount');
        $profit_lss = Db::name('server_lss')->where(['is_action'=>1])->sum('server_amount');
        $insert_data +=[
            "profit_cd" =>$profit_cd,
            "profit_lss" =>$profit_lss
        ];
        //Cards Data-----------------------------------------------------------------------------
        $card_list_all = Db::name('cards')->field(
            "sum(open_amount) open_amount,
                    sum(server_amount) server_amount,
                    sum(balance) balance,
                    sum(balance_account) balance_account,
                    sum(refund_amount) refund_amount")
            ->where("user_id !=1")->find();
        $open_amount_all   = empty($card_list_all['open_amount'])? 0.00: $card_list_all['open_amount'];
        $server_amount_all = empty($card_list_all['server_amount'])? 0.00: $card_list_all['server_amount'];
        $refund_amount_all = empty($card_list_all['refund_amount'])? 0.00: $card_list_all['refund_amount'];
        $insert_data +=[
            'open_amount_all' => $open_amount_all,
            'server_amount_all' => $server_amount_all,
            'balance_all' => empty($card_list_all['balance'])? 0.00: $card_list_all['balance'],
            'balance_account_all' => empty($card_list_all['balance_account'])? 0.00: $card_list_all['balance_account'],
            'refund_amount_all' => $refund_amount_all,
            'profit'     => getSprintf($open_amount_all + $server_amount_all + $refund_amount_all)
        ];
        $result = Db::name("home_data_index")->save($insert_data);
        return $result;
    }

    public static function getHomeData($param = NULL)
    {
        $all_data  = [];
        $is_all_up = 1;
        $insert_data = [
            "data" => "updateAll",
            "ctime"=> getUtcTime()
        ];
        ini_set('memory_limit', '-1');

        if(!empty($param)){
            $data_param = $param['datetime'] ?? 'updateAll';
            $is_all_up  = $param['is_all_up'];
            if($is_all_up != 1){
                $time_list = explode('_' , $data_param);
                $start_time = strtotime(trim($time_list[0]) . " 00:00:00") - 8*60*60;
                $end_time   = strtotime(trim($time_list[1]) . " 23:59:59") - 8*60*60;
                $all_data['start_time'] = $start_time;
                $all_data['end_time'] = $end_time;
                $all_data['start_time_str'] = trim($time_list[0]) . " 00:00:00";
                $all_data['end_time_str'] = trim($time_list[1]) . " 23:59:59";
            }
            $insert_data = [
                "data" => $data_param,
                "ctime"=> getUtcTime()
            ];
        }
        //更新全部 1=是，0=否
        if($is_all_up == 1){
            $all_data = [];
        }

        if($is_all_up == 1){
            //all===========================================================================================
            $profit_cd = Db::name('server_cd')->where(['is_action'=>1])->sum('server_amount');
            $profit_lss = Db::name('server_lss')->where(['is_action'=>1])->sum('server_amount');
            $insert_data +=[
                "profit_cd" =>$profit_cd,
                "profit_lss" =>$profit_lss
            ];
            //Cards Data-----------------------------------------------------------------------------
            $card_list_all = Db::name('cards')->field(
                "sum(open_amount) open_amount,
                    sum(server_amount) server_amount,
                    sum(balance) balance,
                    sum(balance_account) balance_account,
                    sum(refund_amount) refund_amount")
                ->where("user_id !=1")->find();
            $card_list_com = Db::name('cards')->field(
                "sum(balance) balance,
                    sum(balance_account) balance_account")
                ->where("user_id !=1 and bank_type !=3")->find();
            $card_list_lss = Db::name('cards')->field(
                "sum(balance) balance,
                    sum(balance_account) balance_account")
                ->where("user_id !=1 and bank_type =3")->find();
            $open_amount_all   = empty($card_list_all['open_amount'])? 0.00: $card_list_all['open_amount'];
            $server_amount_all = empty($card_list_all['server_amount'])? 0.00: $card_list_all['server_amount'];
            $refund_amount_all = empty($card_list_all['refund_amount'])? 0.00: $card_list_all['refund_amount'];
            $insert_data +=[
                'open_amount_all' => $open_amount_all,
                'server_amount_all' => $server_amount_all,
                'balance_all' => empty($card_list_all['balance'])? 0.00: $card_list_all['balance'],
                'balance_account_all' => empty($card_list_all['balance_account'])? 0.00: $card_list_all['balance_account'],
                'refund_amount_all' => $refund_amount_all,
                'balance_com' => empty($card_list_com['balance'])? 0.00: $card_list_com['balance'],
                'balance_account_com' => empty($card_list_com['balance_account'])? 0.00: $card_list_com['balance_account'],
                'balance_lss' => empty($card_list_lss['balance'])? 0.00: $card_list_lss['balance'],
                'balance_account_lss' => empty($card_list_lss['balance_account'])? 0.00: $card_list_lss['balance_account'],
                'profit'     => getSprintf($open_amount_all + $server_amount_all + $refund_amount_all)
            ];
            $card_count_list= Db::name('cards')->field('count(id) count , bank_type')
                ->group('bank_type')->select()->toArray();
            $card_1_count =0;
            $card_2_count =0;
            $card_3_count =0;
            if($card_count_list){
                foreach ($card_count_list as $v_count){
                    switch ($v_count['bank_type']){
                        case '1':
                            $card_1_count = $v_count['count'];
                            break;
                        case '2':
                            $card_2_count  = $v_count['count'];
                            break;
                        case '3':
                            $card_3_count  = $v_count['count'];
                            break;
                    }
                }
            }
            $insert_data +=[
                'card_count_com'    => $card_1_count + $card_2_count,
                'card_count_lss'    => $card_3_count,
                'cand_count_total'  => $card_1_count + $card_2_count + $card_3_count
            ];

            //充值
            $fund_list = Db::name('fund_check')->field("sum(amount) amount , pay_type")
                ->group("pay_type")->select()->toArray();
            $fund_zfb =0;
            $fund_zfb_sm =0;
            $fund_wx =0;
            $fund_czm =0;
            $fund_admin =0;
            if($fund_list){
                foreach ($fund_list as $v_fund){
                    switch ($v_fund['pay_type']){
                        case '1'://支付宝
                            $fund_zfb = $v_fund['amount'];
                            break;
                        case '2'://支付宝扫码
                            $fund_zfb_sm  = $v_fund['amount'];
                            break;
                        case '3'://微信
                            $fund_wx  = $v_fund['amount'];
                            break;
                        case '4'://充值码
                            $fund_czm  = $v_fund['amount'];
                            break;
                        case '0'://管理员
                            $fund_admin  = $v_fund['amount'];
                            break;
                    }
                }
            }
            $insert_data +=[
                "fund_zfb" =>$fund_zfb,
                "fund_zfb_sm" =>$fund_zfb_sm,
                "fund_wx" =>$fund_wx,
                "fund_czm" =>$fund_czm,
                "fund_admin" =>$fund_admin,
            ];
            //所有用户账户余额
            $total_user_amount = Db::name('user')->where("id != 1")->sum('balance');
            $insert_data +=[
                "user_balance_total" =>$total_user_amount
            ];

            //card 状态统计
            $card_num_1_active    = 0;
            $card_num_1_sus       = 0;
            $card_num_1_ter       = 0;
            $card_num_2_active    = 0;
            $card_num_2_sus       = 0;
            $card_num_2_ter       = 0;
            $card_num_3_active    = 0;
            $card_num_3_sus       = 0;
            $card_num_3_ter       = 0;
            $card_num_list           = Db::name('cards')->field('count(*) num,status,bank_type')
                ->group('status,bank_type')->select()->toArray();

            if($card_num_list){
                foreach ($card_num_list as $v_num){
                    switch ($v_num['bank_type']){
                        case '1':
                            switch ($v_num['status']){
                                case '1':
                                    $card_num_1_active = $v_num['num'];
                                    break;
                                case '2':
                                    $card_num_1_sus  = $v_num['num'];
                                    break;
                                case '3':
                                    $card_num_1_ter  = $v_num['num'];
                                    break;
                            }
                            break;
                        case '2':
                            switch ($v_num['status']){
                                case '1':
                                    $card_num_2_active = $v_num['num'];
                                    break;
                                case '2':
                                    $card_num_2_sus  = $v_num['num'];
                                    break;
                                case '3':
                                    $card_num_2_ter  = $v_num['num'];
                                    break;
                            }
                            break;
                        case '3':
                            switch ($v_num['status']){
                                case '1':
                                    $card_num_3_active = $v_num['num'];
                                    break;
                                case '2':
                                    $card_num_3_sus  = $v_num['num'];
                                    break;
                                case '3':
                                    $card_num_3_ter  = $v_num['num'];
                                    break;
                            }
                            break;
                    }
                }
            }
            $insert_data +=[
                "card_num_active_com" => $card_num_1_active + $card_num_2_active,
                "card_num_sus_com" => $card_num_1_sus + $card_num_2_sus,
                "card_num_ter_com" => $card_num_1_ter + $card_num_2_ter,
                "card_num_active_lss" => $card_num_3_active,
                "card_num_sus_lss" => $card_num_3_sus,
                "card_num_ter_lss" => $card_num_3_ter,
                "card_num_active_total" => $card_num_1_active + $card_num_2_active + $card_num_3_active,
                "card_num_sus_total" => $card_num_1_sus + $card_num_2_sus + $card_num_3_sus,
                "card_num_ter_total" => $card_num_1_ter + $card_num_2_ter + $card_num_3_ter
            ];
        }
        $where_add = '';
        $where_add_str = '';
        if(!empty($all_data)){
            $start_time     = $all_data['start_time'];
            $end_time       = $all_data['end_time'];
            $start_time_str = $all_data['start_time_str'];
            $end_time_str   = $all_data['end_time_str'];

            $where_add      = " and ( ctime between {$start_time} and {$end_time} )";
            $where_add_str  = " and ( ctime between '{$start_time_str}' and '{$end_time_str}' )";
        }
        $insert_data['total_refund_amount']    = getSprintf(Db::name('cards_trans_credit')
            ->where("credit_status =1")->sum('amount'));
        $insert_data['total_refund_amount_un'] = getSprintf(Db::name('cards_trans_credit')
            ->where("credit_status =0")->sum('amount'));
        $insert_data['total_refund_amount_556766'] = getSprintf(Db::name('cards_trans_credit_cd')
            ->sum('amount'));
        $insert_data['total_refund_amount_lss']    = getSprintf(Db::name('cards_trans_credit_lss')
            ->where("credit_status =1")->sum('amount'));
//        $tran_list         = self::getTranData(
//            $where_add_str);
//        $insert_data['total_auth_amount']      = getSprintf($tran_list['amount_auth']);
//        $insert_data['total_decline_amount']   = getSprintf($tran_list['amount_decline']);
//        $insert_data['total_post_amount']      = getSprintf($tran_list['amount_post']);
//        $insert_data['total_reversal_amount']  = getSprintf($tran_list['amount_reversal']);
//        $insert_data['total_refund_amount']    = getSprintf($tran_list['amount_credit']);
//        $insert_data['total_refund_amount_un'] = getSprintf($tran_list['amount_credit_un']);
//        $insert_data['total_refund_amount_556766'] = getSprintf($tran_list['amount_credit_556766']);
//        $insert_data['total_tran_amounts']     = getSprintf($tran_list['amount_auth'] + $tran_list['amount_post'] - abs($tran_list['amount_credit']) - abs($tran_list['amount_credit_556766']));
//
//        $insert_data['total_auth_amount_lss']      = getSprintf($tran_list['amount_auth_lss']);
//        $insert_data['total_decline_amount_lss']   = getSprintf($tran_list['amount_decline_lss']);
//        //记录反了， amount_post_lss 记录的是reversal  , amount_reversal_lss 记录的是 post
//        $insert_data['total_post_amount_lss']      = getSprintf($tran_list['amount_post_lss']);
//        $insert_data['total_reversal_amount_lss']  = getSprintf($tran_list['amount_reversal_lss']);
//        $insert_data['total_refund_amount_lss']    = getSprintf($tran_list['amount_credit_lss']);
//        $insert_data['total_tran_amounts_lss']     = getSprintf($tran_list['amount_auth_lss'] + $tran_list['amount_post_lss'] - $tran_list['amount_credit_lss'] - $tran_list['amount_reversal_lss']);

        //funding amount all
        $funding_complete = Db::name('fund_check')
            ->where('check_status = 1 ' . ($where_add ?? ''))->sum('amount');
        $insert_data['funding_amount_all'] = getSprintf($funding_complete);
        $result = Db::name("home_data")->save($insert_data);
        return $result;
    }

    public static function getTranData($where_add = '')
    {
        $where  ="user_id != 1 ";
        $where .= $where_add;
        $tran_list = Db::name('cards_trans')
            ->field('amount_auth,amount_post,tran_status,reversal_flag,ctime,card_num,bank_type')
            ->where($where)
            ->select()->toArray();
        //银12数据
        $amount_auth = 0.00;
        $amount_post = 0.00;
        $amount_reversal = 0.00;
        $amount_credit = 0.00;
        $amount_credit_un = 0.00;
        $amount_credit_556766 = 0.00;
        $amount_decline = 0.00;
        //银3数据
        $amount_auth_lss = 0.00;
        $amount_post_lss = 0.00;
        $amount_reversal_lss = 0.00;
        $amount_credit_lss = 0.00;
        $amount_decline_lss = 0.00;

        if ($tran_list) {
            foreach ($tran_list as $v) {
                $bank_type      = $v['bank_type'];
                $reversal_flag  = $v['reversal_flag'];
                $ctime          = $v['ctime'];
                if($bank_type == 3){
                    switch ($v['tran_status']) {
                        case 'Authorized':
                            $amount_auth_lss += $v['amount_auth'];
                            break;
                        case 'Reversal':
                            $amount_post_lss += $v['amount_auth'];
                            break;
                        case 'Posted':
                            $amount_reversal_lss += $v['amount_post'];
                            break;
                        case 'Credit':
                            $amount_credit_lss += $v['amount_post'];
                            break;
                        case 'Declined':
                            $amount_decline_lss += $v['amount_auth'];
                            break;
                    }
                }else{
                    switch ($v['tran_status']) {
                        case 'Authorized':
                            if ($reversal_flag == 'N') {
                                $amount_auth += $v['amount_auth'];
                            } else {
                                $amount_reversal += $v['amount_auth'];
                            }
                            break;
                        case 'Posted':
                            $amount_post += $v['amount_post'];
                            break;
                        case 'Credit':
                            $card_num6 = substr($v['card_num'], 0, 6);
                            if ($card_num6 == '556766') {
                                $amount_credit_556766 += $v['amount_post'];
                            } else {
                                $credit_status = Db::name('cards_trans_credit')
                                    ->where(['ctime' => $ctime, 'amount' => abs($v['amount_post'])])->value('credit_status');
                                if ($credit_status == 1) {
                                    $amount_credit += $v['amount_post'];
                                } else {
                                    $amount_credit_un += $v['amount_post'];
                                }
                            }
                            break;
                        case 'Declined':
                            $amount_decline += $v['amount_auth'];
                            break;
                    }
                }

            }
        }
        return [
            'amount_auth' => $amount_auth,
            'amount_post' => $amount_post,
            'amount_reversal' => $amount_reversal,
            'amount_credit' => $amount_credit,
            'amount_credit_un' => $amount_credit_un,
            'amount_credit_556766' => $amount_credit_556766,
            'amount_decline' => $amount_decline,
            'amount_auth_lss' => $amount_auth_lss,
            'amount_post_lss' => $amount_post_lss,
            'amount_reversal_lss' => $amount_reversal_lss,
            'amount_credit_lss' => $amount_credit_lss,
            'amount_decline_lss' => $amount_decline_lss,
        ];
    }

    public function homeList($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $list = Db::name('home_data_index')
            ->order('id desc')
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();
        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

    public function homeListTwo($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $list = Db::name('home_data')
            ->order('id desc')
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();
        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

}